<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <!-- <el-form-item label="分类id" prop="classifyId">
          <el-input
            v-model="queryParams.classifyId"
            placeholder="请输入分类id"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="总销售数量" prop="totalSellCounts">
          <el-input
            v-model="queryParams.totalSellCounts"
            placeholder="请输入总销售数量"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
      <el-form-item label="商品名称" prop="goodName">
        <el-input
          v-model="queryParams.goodName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="一级分类" prop="oneId">
        <el-select
          v-model="queryParams.oneId"
          filterable
          placeholder="请选择"
          @change="(row) => getline(row, 'select')"
          @keyup.enter.native="handleQuery"
        >
          <el-option
            v-for="item in goodclassifyListOne"
            :key="item.deptName"
            :label="item.deptName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <!--      <el-form-item label="二级分类" prop="twoId">-->
      <!--        <el-select v-model="queryParams.twoId" filterable placeholder="请选择" @change="(row) => getlineTwo(row, 'select')"-->
      <!--          @keyup.enter.native="handleQuery">-->
      <!--          <el-option v-for="item in goodclassifyListTwo" :key="item.deptName" :label="item.deptName"-->
      <!--            :value="item.id"></el-option>-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="三级分类" prop="classifyId">-->
      <!--        <el-select v-model="queryParams.classifyId" filterable placeholder="请选择" @change="getlineThree"-->
      <!--          @keyup.enter.native="handleQuery">-->
      <!--          <el-option v-for="item in goodclassifyListThree" :key="item.deptName" :label="item.deptName"-->
      <!--            :value="item.id"></el-option>-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <!-- <el-form-item label="批发价" prop="tradePrice">
          <el-input
            v-model="queryParams.tradePrice"
            placeholder="请输入批发价"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="零售价" prop="retailPrice">
          <el-input
            v-model="queryParams.retailPrice"
            placeholder="请输入零售价"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="会员价" prop="memberPrice">
          <el-input
            v-model="queryParams.memberPrice"
            placeholder="请输入会员价"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="商品图片" prop="goodImg">
          <el-input
            v-model="queryParams.goodImg"
            placeholder="请输入商品图片"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="详情图片" prop="goodDetail">
          <el-input
            v-model="queryParams.goodDetail"
            placeholder="请输入详情图片"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="描述" prop="describe">
          <el-input
            v-model="queryParams.describe"
            placeholder="请输入描述"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd()"
          v-hasPermi="['system:model:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:model:edit']"
          >修改</el-button>
        </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:model:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:model:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:model:export']"
          >导入</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="modelList"
      @selection-change="handleSelectionChange"
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="一级分类" align="center" prop="oneName" />
      <!--      <el-table-column label="二级分类" align="center" prop="twoName" />-->
      <!--      <el-table-column label="三级分类" align="center" prop="classifyName" />-->
      <el-table-column label="商品名称" align="center" prop="goodName" />
      <el-table-column label="批发价(￥)" align="center" prop="tradePrice" />
      <el-table-column label="零售价(￥)" align="center" prop="retailPrice" />
      <el-table-column label="会员价(￥)" align="center" prop="memberPrice" />
      <el-table-column label="商品图片" align="center" prop="goodImg">
        <template slot-scope="scope">
          <image-preview :src="scope.row.goodImg" :width="50" :height="50" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="详情图片" align="center" prop="goodDetail">
        <template slot-scope="scope">
          <image-preview :src="scope.row.goodDetail" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="describe" /> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-if="scope.row.parentId == 0"
            v-hasPermi="['system:model:add']"
            >新增子模板</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:model:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:model:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品模板对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="90px"
        :disabled="false"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item
              label="一级分类"
              prop="oneId"
              v-if="title == '添加商品模板'"
            >
              <el-select
                v-model="form.oneId"
                placeholder="请选择"
                filterable
                @change="getline"
              >
                <el-option
                  v-for="item in goodclassifyListOne"
                  :key="item.deptName"
                  :label="item.deptName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="二级分类" prop="twoId">-->
          <!--              <el-select v-model="form.twoId" placeholder="请选择" filterable @change="getlineTwo">-->
          <!--                <el-option v-for="item in goodclassifyListTwo" :key="item.deptName" :label="item.deptName"-->
          <!--                  :value="item.id"></el-option>-->
          <!--              </el-select>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->

          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="三级分类" prop="classifyId">-->
          <!--              <el-select v-model="form.classifyId" placeholder="请选择" filterable @change="getlineThree">-->
          <!--                <el-option v-for="item in goodclassifyListThree" :key="item.deptName" :label="item.deptName"-->
          <!--                  :value="item.id"></el-option>-->
          <!--              </el-select>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="商品名称" prop="goodName">
              <el-input
                v-model="form.goodName"
                placeholder="请输入名称"
                style="width: 97.5%"
              />
              <!-- v-if="!distinguish" <el-select v-else v-model="form.goodName" clearable filterable placeholder="请输入名称" style="width: 97.5%;"
                @change="getlineFour" :filter-method="filterMethod">
                <el-option v-for="item in goodclassifyListFour" :key="item.id" :label="item.goodName"
                  :value="item.id"></el-option>
              </el-select> -->
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <img :src="'https://fx.fangxi666.com/prod-api/'+form.goodImg " alt="" v-else style="width: 10vw;"> -->
        <el-form-item
          :label="title != '添加商品模板' ? '规格图片' : '商品图片'"
          prop="goodImg"
        >
          <image-upload v-model="form.goodImg" :limit="1" />
        </el-form-item>
        <el-form-item
          v-if="title == '添加商品模板'"
          :label="title != '添加商品模板' ? '规格图片' : '详情图片'"
          prop="goodDetail"
        >
          <image-upload v-model="form.goodDetail" />
        </el-form-item>
        <!-- <el-form-item label="详情描述" prop="goodText">
          <el-input v-model="form.goodText" type="textarea" placeholder="请输入内容" />
        </el-form-item> -->
        <!-- <el-form-item label="详情">
          <editor v-model="form.goodDetail" :min-height="192" />
        </el-form-item> -->
        <!-- <el-form-item label="描述" prop="goodDesc">
          <el-input
            v-model="form.goodDesc"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item> -->

        <el-row>
          <!-- <el-col :span="8">
            <el-form-item label="批发价" prop="tradePrice">
              <el-input v-model="form.tradePrice" placeholder="请输入批发价" />
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item
              label="零售价"
              prop="retailPrice"
              v-if="title != '添加商品模板'"
            >
              <el-input v-model="form.retailPrice" placeholder="请输入零售价" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item
              label="库存"
              prop="inventory"
              v-if="title != '添加商品模板'"
            >
              <el-input v-model="form.inventory" placeholder="请输入库存" />
            </el-form-item>
          </el-col>

          <!-- <el-col :span="8">
            <el-form-item label="会员价" prop="memberPrice">
              <el-input v-model="form.memberPrice" placeholder="请输入会员价" />
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <!-- <el-col :span="12">
            <el-form-item label="数量" prop="counts">
              <el-input v-model="form.counts" placeholder="请输入数量" />
            </el-form-item>
          </el-col> -->
        </el-row>
        <!-- <el-form-item label="单位[计量]" prop="units" v-if="!form.oneId">
          <el-input v-model="form.units" placeholder="请输入单位" />
        </el-form-item> -->
        <div v-if="title == '添加商品模板' || title == '修改商品模板'">
          <div
            style="width: 100%"
            v-for="(item, i) in form.paramsNewArr"
            :key="i"
          >
            <el-row>
              <el-col :span="10">
                <el-form-item
                  label="参数名称"
                  :prop="`paramsNewArr[${i}].paramsName`"
                  :rules="[
                    {
                      required: true,
                      message: '输入参数名称',
                      trigger: 'change',
                    },
                  ]"
                >
                  <el-input
                    v-model="item.paramsName"
                    placeholder="请输入单位"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item
                  label="参数内容"
                  :prop="`paramsNewArr[${i}].paramsValue`"
                  :rules="[
                    {
                      required: true,
                      message: '输入参数内容信息',
                      trigger: 'change',
                    },
                  ]"
                >
                  <el-input
                    v-model="item.paramsValue"
                    placeholder="请输入单位"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <div>
                  <i
                    style="
                      cursor: pointer;
                      margin-left: 6px;
                      margin-top: 5px;
                      font-size: 20px;
                    "
                    v-if="form.paramsNewArr.length > 1"
                    class="el-icon-remove-outline"
                    @click="del(i)"
                  ></i>
                  <i
                    style="
                      cursor: pointer;
                      margin-left: 6px;
                      margin-top: 5px;
                      font-size: 20px;
                    "
                    class="el-icon-circle-plus-outline"
                    @click="add"
                  ></i>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
        <!-- <el-form-item label="重量" prop="weight" v-if="title == '添加商品模板子模版'">
          <el-input v-model="form.weight" placeholder="请输入重量" />
        </el-form-item>
        <el-form-item label="重量单位" prop="weightUnits" v-if="title == '添加商品模板子模版'">
          <el-input v-model="form.weightUnits" placeholder="请输入重量单位" />
        </el-form-item>
        <el-form-item label="店内码" prop="articleNumber" v-if="title == '添加商品模板子模版'">
          <el-input v-model="form.articleNumber" placeholder="请输入店内码" />
        </el-form-item>
        <el-form-item label="货架码" prop="shelfCode" v-if="title == '添加商品模板子模版'">
          <el-input v-model="form.shelfCode" placeholder="请输入货架码" />
        </el-form-item>
        <el-form-item label="起购数" prop="minimumPurchaseQuantity" v-if="title == '添加商品模板子模版'">
          <el-input v-model="form.minimumPurchaseQuantity" placeholder="请输入起购数" />
        </el-form-item> -->
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 导入商品模板对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div> -->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板</el-link> -->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listModel,
  getModel,
  delModel,
  addModel,
  updateModel,
  threeSelectModel,
  fourSelectModel,
} from "@/api/fx/model";
import { getToken } from "@/utils/auth";
import { listGoodclassify } from "@/api/fx/goodclassify";

export default {
  name: "Model",
  data() {
    return {
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/fx/model/importMb",
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      modelIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品模板表格数据
      modelList: [],
      // 弹出层标题
      title: "",
      distinguish: false,
      // 是否显示弹出层
      open: false,
      goodclassifyList: [],
      goodclassifyListOne: [],
      goodclassifyListTwo: [],
      goodclassifyListThree: [],
      goodclassifyListFour: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        oneId: null,
        classifyName: null,
        totalSellCounts: null,
        goodName: null,
        tradePrice: null,
        retailPrice: null,
        memberPrice: null,
        goodImg: null,
        goodDetail: null,
        describe: null,
      },
      // 表单参数
      form: {
        paramsNewArr: [{ paramsName: "", paramsValue: "" }],
      },
      // 表单校验
      rules: {
        oneId: { required: true, message: "请选择一级分类", trigger: "blur" },
        twoId: { required: true, message: "请选择二级分类", trigger: "blur" },
        classifyId: {
          required: true,
          message: "请选择三级分类",
          trigger: "blur",
        },
        goodName: {
          required: true,
          message: "商品名称不能为空",
          trigger: "blur",
        },
        goodImg: {
          required: true,
          message: "商品图片不能为空",
          trigger: "blur",
        },
        units: { required: true, message: "请输入单位", trigger: "blur" },
        inventory: { required: true, message: "请输入库存", trigger: "blur" },
        // tradePrice: { required: true, message: '批发价不能为空', trigger: 'blur' },
        // retailPrice: { required: true, message: '零售价不能为空', trigger: 'blur' },
        // memberPrice: { required: true, message: '会员价不能为空', trigger: 'blur' },
      },
      isAdd: true,
      isGoodName: true,
      goodclassifyListFours: [],
      goodsImg: null,
    };
  },
  created() {
    this.getList();
    this.getlistGoodclassify();
  },
  methods: {
    //添加评价内容
    add() {
      this.form.paramsNewArr.push({ paramsName: "", paramsValue: "" });
    },
    //删除评价内容
    del(i) {
      this.form.paramsNewArr.splice(i, 1);
    },
    /** 查询商品模板列表 */
    getList() {
      this.loading = true;
      let classifyName = "";
      console.log(this.queryParams.oneId);
      if (this.queryParams.oneId) {
        classifyName = this.goodclassifyListOne.find(
          (item) => item.id == this.queryParams.oneId
        ).deptName;
      }

      const params = {
        ...this.queryParams,
        oneName: classifyName || "",
      };
      listModel(params).then((response) => {
        this.modelList = this.handleTree(response.rows, "id");
        this.total = response.total;
        this.loading = false;
      });
    },

    getlistGoodclassify() {
      listGoodclassify(this.queryParams).then((response) => {
        this.goodclassifyList = response.rows;
        this.goodclassifyListOne = this.goodclassifyList.filter(
          (item) => item.tier == 0
        );
      });
    },
    getline(row, type) {
      //查询分类对应的商品
      this.getlineThree(row);
      this.goodclassifyListTwo = this.goodclassifyList.filter(
        (item) => item.parentId == parseInt(row)
      );
      if (type) {
        this.queryParams.twoId = "";
        this.queryParams.classifyId = "";
      } else {
        this.form.oneName = this.goodclassifyListOne.filter(
          (item) => row == item.id
        )[0]?.deptName;
        this.form.classTwoId = "";
        this.form.classThreeId = "";
      }
    },
    getlineTwo(row, type) {
      this.goodclassifyListThree = this.goodclassifyList.filter(
        (item) => item.parentId == parseInt(row)
      );
      if (type) {
        this.queryParams.classifyId = "";
      } else {
        this.form.twoName = this.goodclassifyListTwo.filter(
          (item) => item.id == row
        )[0]?.deptName;
        this.form.classifyId = "";
      }
    },
    getlineThree(row) {
      fourSelectModel(row).then((res) => {
        // console.log(res, '根据最后一级id查询模板');
        if (res.code == 200) {
          this.goodsImg = res.data.goodImg;
          this.form.goodName = res.data.goodName;
          this.form.goodImg = this.goodsImg;
          console.log(this.form);
          this.goodclassifyListFour = [...res.data.modelList];
          this.goodclassifyListFours = [...res.data.modelList];
          this.saveFormclass(row);
        }
      });
    },
    revertData(convertedData) {
      const newDataList = [];
      const pairs = convertedData.split("。");
      pairs.forEach((pair) => {
        // 同时支持中文冒号和英文冒号
        const separatorIndex = pair.includes("：")
          ? pair.indexOf("：")
          : pair.indexOf(":");

        // 确保找到了分隔符且键名存在
        if (separatorIndex !== -1 && separatorIndex > 0) {
          const paramsName = pair.substring(0, separatorIndex).trim();
          const valuesStr = pair.substring(separatorIndex + 1).trim();

          // 忽略空值
          if (valuesStr) {
            if (valuesStr.includes(",")) {
              // 多值情况：按逗号拆分
              const values = valuesStr.split(",");
              values.forEach((value) => {
                const trimmedValue = value.trim();
                if (trimmedValue) {
                  newDataList.push({
                    paramsName,
                    paramsValue: trimmedValue,
                  });
                }
              });
            } else {
              // 单值情况：直接添加
              newDataList.push({
                paramsName,
                paramsValue: valuesStr,
              });
            }
          }
        }
      });

      return newDataList;
    },

    getlineFour(row) {
      let detail = this.goodclassifyListFour.filter((item) => item.id == row);
      if (
        detail[0].specificationsList &&
        detail[0].specificationsList.length != 0
      ) {
        detail[0].paramsNewArr = this.revertData(detail[0].specifications);
      } else {
        detail[0].paramsNewArr = [
          {
            paramsName: "",
            paramsValue: "",
          },
        ];
      }
      this.form = {
        ...detail[0],
      };
    },
    filterMethod(row) {
      this.form.id = null;
      let list = [];
      this.goodclassifyListFours.forEach((item) => {
        if (item.goodName.indexOf(row) !== -1) {
          list.push(item);
        }
      });
      this.goodclassifyListFour = list;
      // if (list.length == 0) {
      //   this.goodclassifyListFour = [...this.goodclassifyListFours]
      // } else {
      // }
      this.$set(this.form, "goodName", row);
      this.form = {
        ...this.form,
        goodImg: this.goodsImg,
        goodDetail: "",
        goodText: "",
        tradePrice: "",
        retailPrice: "",
        memberPrice: "",
        inventory: "",
      };
    },
    saveFormclass(row) {
      console.log(row + " 测试---------");
      let oneName = this.goodclassifyListOne.filter(
        (item) => this.form.oneId == item.id
      )[0]?.deptName;
      // let twoName = this.goodclassifyListTwo.filter(item => item.id == this.form.twoId)[0]?.deptName
      let oneId = this.form.oneId;
      // let twoId = this.form.twoId
      let goodName = this.form.goodName;
      this.form = { paramsNewArr: [{ paramsName: "", paramsValue: "" }] };
      this.form.oneId = oneId;
      // this.form.twoId = twoId
      this.form.classifyId = oneId;
      this.form.oneName = oneName;
      this.form.twoName = twoName;
      this.form.goodName = goodName;
      this.form.goodImg = this.goodsImg;
      // console.log(this.form)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        classifyId: null,
        totalSellCounts: null,
        goodName: null,
        tradePrice: null,
        retailPrice: null,
        inventory: null,
        classOneId: null,
        classTwoId: null,
        classThreeId: null,
        memberPrice: null,
        goodImg: null,
        goodDetail: null,
        describe: null,
        createTime: null,
        paramsNewArr: [{ paramsName: "", paramsValue: "" }],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      // this.modelIds = selection.map((item) => item.modelId);
      console.log(selection, this.ids, "this.ids");

      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.open = true;
      this.title = "添加商品模板";
      this.distinguish = true;
      this.isAdd = true;
      if (row) {
        this.form.parentId = row.id;
        this.form.oneId = row.oneId;
        this.title = "添加商品规格";
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getModel(id).then((response) => {
        this.isAdd = false;
        if (
          response.data.specificationsList &&
          response.data.specificationsList.length != 0
        ) {
          response.data.paramsNewArr = this.revertData(
            response.data.specifications
          );
        } else {
          response.data.paramsNewArr = [{ paramsName: "", paramsValue: "" }];
        }
        this.form = response.data;
        this.distinguish = false;
        this.open = true;
        this.title = "修改商品模板";
      });
    },
    /** 提交按钮 */

    transformFormData(references) {
      // 用于存储合并后的数据
      const mergedData = {};
      // 遍历原始数据数组
      references.forEach((item) => {
        if (mergedData[item.paramsName]) {
          // 如果该 paramsName 已存在，将 paramsValue 追加到已有值后面
          mergedData[item.paramsName].push(item.paramsValue);
        } else {
          // 如果该 paramsName 不存在，初始化一个数组存储 paramsValue
          mergedData[item.paramsName] = [item.paramsValue];
        }
      });

      const result = [];
      // 遍历合并后的数据对象
      for (const key in mergedData) {
        if (mergedData.hasOwnProperty(key)) {
          // 将 paramsName 和合并后的 paramsValue 按指定格式拼接
          result.push(`${key}:${mergedData[key].join(",")}`);
        }
      }
      return result.join("。");
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.classifyId = this.form.oneId;
          this.form.specifications = this.transformFormData(
            this.form.paramsNewArr
          );
          if (this.form.id != null) {
            addModel(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addModel(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除商品模板编号为"' + ids + '"的数据项？')
        .then(function () {
          return delModel(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作  modelIds: this.ids.join(","), */
    handleExport() {
      this.download(
        "fx/model/export",
        {
          ...this.queryParams,
        },
        `model_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/user/importTemplate",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>
